from PyQt6.QtWidgets import QTabWidget, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout, QWidget, QHeaderView
from PyQt6.QtCore import Qt
import pandas as pd

class ResultTab(QTabWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setTabsClosable(True)
        self.tabCloseRequested.connect(self.close_tab)

        # 添加初始结果页
        self.add_results_tab("结果", "就绪")

    def add_results_tab(self, title, message, dataframes=None):
        """添加新的结果标签页"""
        tab = QWidget()
        layout = QVBoxLayout(tab)

        # 结果表格容器
        self.tables_container = QTabWidget()
        self.tables_container.setTabsClosable(False)

        # 如果有数据，显示数据
        if dataframes:
            for i, df in enumerate(dataframes):
                table_widget = self.create_table_from_dataframe(df)
                self.tables_container.addTab(table_widget, f"结果集 {i+1}")

        # 消息文本框
        self.message_box = QTextEdit()
        self.message_box.setPlainText(message)
        self.message_box.setReadOnly(True)
        self.message_box.setMaximumHeight(100)

        layout.addWidget(self.tables_container, 3)
        layout.addWidget(self.message_box, 1)

        self.addTab(tab, title)
        self.setCurrentWidget(tab)

    def create_table_from_dataframe(self, df):
        """从Pandas DataFrame创建表格部件"""
        table = QTableWidget()
        table.setRowCount(len(df))
        table.setColumnCount(len(df.columns))
        table.setHorizontalHeaderLabels(df.columns)

        # 填充数据
        for row_idx, row in df.iterrows():
            for col_idx, value in enumerate(row):
                item = QTableWidgetItem(str(value))
                item.setFlags(item.flags() ^ Qt.ItemFlag.ItemIsEditable)
                table.setItem(row_idx, col_idx, item)

        # 调整列宽
        table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)

        return table

    def show_results(self, results, message):
        """显示查询结果"""
        self.add_results_tab("结果", message, results)

    def close_tab(self, index):
        """关闭标签页"""
        if self.count() > 1:
            self.removeTab(index)